<template>
  <div class="postpublish">
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="">文章管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>文章发布</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card" style="margin-top: 20px">
      <!-- 文本输入框 -->
      <el-form ref="form" :model="post" label-width="80px">
        <el-form-item label="标题:">
          <el-input v-model="post.title"></el-input>
        </el-form-item>

        <el-form-item label="类型">
          <el-radio-group v-model="post.type">
            <el-radio :label="1">文章</el-radio>
            <el-radio :label="2">视频</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="内容">
          <!-- 文章 -->
          <VueEditor
            :config="config"
            v-if="post.type == 1"
            ref="myeditor"
          ></VueEditor>
          <!-- 视频 -->
          <el-upload
            class="upload-demo"
            :action="axios.defaults.baseURL + '/upload'"
            v-else
            :headers="getToken()"
            :on-success="videoSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传文件视频</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="栏目">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="checkedCates"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="value in cateList"
              :label="value.id"
              :key="value.id"
              >{{ value.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="封面">
          <el-upload
            :action="axios.defaults.baseURL + '/upload'"
            list-type="picture-card"
            :headers="getToken()"
            :on-success="coverSuccess"
            :on-remove="coverRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <el-button type="primary" @click="publishPost">发布</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import VueEditor from "vue-word-editor";
import "quill/dist/quill.snow.css";
import axios from "@/utils/request.js";

import { getCateList } from "@/apis/category.js";
import { publishThisPost } from "@/apis/post.js";
export default {
  components: { VueEditor },
  data() {
    return {
      axios,
      post: {
        title: "", //标题
        content: "", //文章内容 文章-》内容  视频-》路径
        categories: "", //文章所属栏目 id数组
        cover: [], //封面，也是id集合
        type: 1,
      },
      config: {
        // 上传图片的配置
        uploadImage: {
          url: axios.defaults.baseURL + "/upload",
          name: "file",
          //   传递token
          headers: this.getToken(),
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess(res, insert) {
            insert(axios.defaults.baseURL + res.data.data.url);
          },
        },
      },
      cateList: [],
      checkedCates: [], //当前用户所选择的复选框选项值的集合：id集合
      checkAll: false,
      isIndeterminate: false,
    };
  },
  async mounted() {
    this.cateList = (await getCateList()).data.data;
    // 头条和关注不参与选择
    if (localStorage.getItem("heima_back_token_61")) {
      this.cateList.splice(0, 2);
    } else {
      this.cateList.splice(0, 1);
    }
  },
  methods: {
    // 视频上传成功之后回调
    videoSuccess(response) {
      // 对于视频类型，content中存储的是视频在服务器的路径
      this.post.content = this.axios.defaults.baseURL + response.data.url;
    },
    // 我们所使用的组件，它可以实现文件的上传
    // 但是：
    // 它并没有使用我们自己封装的axios,而是内部自己封装了异步操作，意味着我们添加的拦截器，它根本就不会经过
    // 所以我们需要使用组件内置的headers来实现token的传递
    // 获取token
    getToken() {
      let token = localStorage.getItem("heima_back_token_61");
      return { Authorization: token };
    },
    // 发布
    async publishPost() {
      // 获取富文本框内容
      if (this.post.type == 1) {
        // this.$refs.ref属性值.editor.root.innerHTML
        this.post.content = this.$refs.myeditor.editor.root.innerHTML;
      }
      // 栏目数据进行改造，改造为对象的形式[1,2,3]>>[{id:1},{id:2}]
      this.post.cateList = this.checkedCates.map((v) => {
        return { id: v };
      });
      // console.log(this.post);
      // 发布文章
      let res = await publishThisPost(this.post);
      console.log(res);
      if (res.data.message == "文章发布成功") {
        this.$message.success("文章发布成功");
        this.$router.push({ name: "postList" });
      }
    },
    // 栏目
    handleCheckAllChange(val) {
      this.checkedCates = val
        ? this.cateList.map((v) => {
            return v.id;
          })
        : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      // value是当前用户所选中的所有复选框所对应的id数组
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cateList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cateList.length;
    },
    // 封面
    coverSuccess(response) {
      // 要将当前文件存储在服务器中的id添加到cover中，而且存储的第id，对象形式
      this.post.cover.push({ id: response.data.id });
    },
    // 封面移除，要从数据中移除
    coverRemove(file, fileList) {
      let id = file.response.data.id;
      this.post.cover = this.post.cover.filter((v) => {
        return v.id !== id;
      });
    },
  },
};
</script>

<style>
</style>